import axios from 'axios';
import { deepCopyObj, copyObjBySelf, deepCopyObjArray, clearObject } from '../../../assets/js/help.js';
import { rejects } from 'assert';

function getFontCss(treeId, treeNode) {
  return !!treeNode.highlight
    ? {
        color: '#A60000',
        'font-weight': 'bold'
      }
    : {
        color: '',
        'font-weight': ''
      };
}

export default {
  data() {
    var validatePrice = (rule, value, callback) => {
      if (value == 0) {
        return callback();
      }
      if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/.test(value)) {
        return callback(new Error('请输入正确的金额'));
      } 
      callback();
    };
    var validateSellFromTo = (rule, value, callback) => {
      if (value == null || value == '' || value == ',') {
        return callback(new Error('请选择可销售时间'));
      }
      callback();
    };
    var validateValidFromTo = (rule, value, callback) => {
      if (this.mouthTicketData.ticketModalName == '创建线上月票') {
        if (value == null || value == '' || value == ',') {
          return callback(new Error('请选择有效期'));
        }
      }
      callback();
    };
    var validateParkJson = (rule, value, callback) => {
      var self = this;
      if (!self.tableData.parkItems.length) {
        return callback(new Error('请选择月票的通行权限'));
      }
      callback();
    };
    var validateMaxSellNum = (rule, value, callback) => {
      var self = this;
      if (self.mouthTicketData.baseTicketData.maxSellLimit == 'YES') {
        if (value === null || value === '') {
          return callback(new Error('数量不能为空'));
        }
        if (!/^[1-9]+[0-9]*$/.test(value)) {
          return callback(new Error('请输入大于0的数量'));
        }
        if (self.mouthTicketData.baseTicketData.sellNum > 0 && value < self.mouthTicketData.baseTicketData.sellNum) {
          return callback(new Error('请输入大于或等于已售数量的月票数量'));
        }
      }
      callback();
    };
    var validateInviteCarTotal = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('数量不能为空'));
      }
      if(value==='0' || value===0){
        callback();
      }
      if (!/^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error('请输入大于等于0的数量'));
      }
      callback();
    };
    var validateRenewFormerDays = (rule, value, callback) => {
      var self = this;
      if (self.mouthTicketData.baseTicketData.renewFormerDays) {
        if (value === null || value === '') {
          return callback(new Error('数量不能为空'));
        }
        if (!/^[1-9]+[0-9]*$/.test(value)) {
          return callback(new Error('请输入大于等于0的数量'));
        }
      }
      callback();
    };
    var today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 23:59:59'))];
    return {
      parkingLotChannelTreeData: [], //停车场通道树数据
      parkingLotUrl: '/vip/vipType/getChannelAuthTreeMultiPark.do', //停车场-通道数据url
      modalStatus: '', //模态框状态(1:创建;2:编辑;3:查看)
      selectedParkingLot: '', //已选择的停车场树数据
      selectedParkingLotStr: '', //已选择停车场
      discountIndexArr: [1], //折扣优惠
      moneyIndexArr: [1], //金额优惠
      options4: [], //月票凭证下拉列表
      configEdit: null,
      forceEdit: null,
      checkLast: null,
      supportParkList: [],
      financialParkId: '',
      enableParkSysType: true,
      supportPark: {
        theadsInfo: [
          {
            index: 0,
            isShow: false,
            prop: 'parkName',
            text: '停车场',
            minWidth: 120
          },
          {
            index: 1,
            isShow: false,
            prop: 'parkVipTypeName',
            text: '绑定VIP类型',
            minWidth: 120
          },
          {
            index: 2,
            isShow: false,
            prop: 'isFinancialPark',
            text: '财务主体',
            minWidth: 120
          }
        ]
      },
      synchronismDetialList: [],
      synchronismDetial: {
        theadsInfo: [
          {
            index: 0,
            isShow: false,
            prop: 'parkName',
            text: '停车场',
            minWidth: 180
          },
          {
            index: 1,
            isShow: false,
            prop: 'sendTime',
            text: '同步时间',
            minWidth: 180
          },
          {
            index: 2,
            isShow: false,
            prop: 'sendStatusName',
            text: '同步结果',
            minWidth: 120
          },
          {
            index: 2,
            isShow: false,
            prop: 'respDesc',
            text: '失败原因',
            minWidth: 400
          },
          {
            index: 2,
            isShow: false,
            prop: 'resend',
            text: '操作',
            minWidth: 120
          }
        ]
      },
      //显示以及语音-aa
      showMessage_: null,
      showMessage: {
        validInWarnOut: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\%VM',
              voice: '%P%VM'
            },
            hard: {
              id: null,
              text: '%P\\%VM请稍候',
              voice: '%P%VM请稍候'
            }
          },
          carOut: {
            easy: {
              id: null,
              text: '%P\\%VM',
              voice: '%P%VM'
            },
            hard: {
              id: null,
              text: '%P\\%VM请稍候',
              voice: '%P%VM请稍候'
            }
          }
        },
        validInWarnIn: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            },
            hard: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            }
          },
          carOut: {
            easy: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            },
            hard: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            }
          }
        },
        validOutDelIn: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            },
            hard: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            }
          },
          carOutPay: {
            easy: {
              id: null,
              text: '%VM已过期\\应缴费%C元',
              voice: '%VM已过期应缴费%C元'
            },
            hard: {
              id: null,
              text: '%VM已过期\\应缴费%C元',
              voice: '%VM已过期应缴费%C元'
            }
          },
          carOutNoPay: {
            easy: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            },
            hard: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            }
          }
        }
      },
      //高级配置-aaa
      vipTypeData: {
        id: null,
        customVipName: '',
        settlementType: 0,
        settlementAmount: null,
        isDynamicMode: 0,
        dynamicCarportNumber: null,
        isDatePrivilege: 0,
        isTimePrivilege: 0,
        privilegeTimePeriod: null,
        isChargeGroupRelated: 0,
        chargeGroupCode: null,
        vipGroupType: 0,
        dynamicFullLimit: 0,
        dynamicCarNumber: null,
        vipNearExpiredDayThreshold: '10',
        vipDeleteExpiredDayThreshold: 0,
        openVipFullLimit: 0,
        vipFullLimitValue: 0,
        vipFullOpenModel: 0,
        vipRecoverTime: null,
        priTimeArr: today,
        priTimeArrFrom: '',
        priTimeArrTo: '',
        priDateArrStr: '',
        parkId: '',
        parkName: '',
        channelAuthTree: '',
        channelSeqList: [],
        autoSwitchVip: 0,
        offLine: 1
      },
      editModelReadonly: false,
      isShowTips: false,
      mouthTicketData: {
        parkingLotName: '', //所选停车场名
        tabName: 'basicTab',
        ticketModalName: '',
        //基础信息-a
        baseTicketData: {
          id: '',
          parkSysType: '', //停车场类型(0:vems;1:智泊云;100:路边停车)
          ticketName: '', //月票名称
          ticketType: '', //线上开通(INNER:对内月票;OUTTER:对外月票)
          renew: 1, //过期续费 0:不允许;1:允许(默认是1)
          price: '', //月票单价
          renewMethod: 'NATURAL_MONTH', //有效期类型
          maxSellLimit: 'YES', //月票数量(有限/无限)
          maxSellNum: '', //月票数量
          sellNum: '', //已售数量
          financialParkId: '', //记录哪一个停车场为财务主体
          parkJson: [], //每条记录都记录 停车场的ID和对应的VIP类型的关系
          remark: '', //备注
          renewFormerDays: 0, //向前续费天数
          inviteCarTotal: 3, //访客授权车位数
          certifiRuleId: null, //月票凭证
          continueBuyFlag: 1, //连续续费方式
          supportVirtualCarcode: 0, //无牌车(0:不支持;1:支持)
          offLine: 1, //离线月票(0:不支持;1:支持)
          ticketDesc: '',
          sellFromTo: [],
          sellingPic: '',
          selloutPic: '',
          sellingPicName: '',
          selloutPicName: '',
          parkVipTypeJson: ''
        }
      },
      discountOption: {
        //折扣优惠
        unitPrice: '', //单价
        month1: '', //月份
        discount1: '', //折扣
        money1: '', //金额
        phoneStr1: '', //手机端显示

        month2: '', //月份
        discount2: '', //折扣
        money2: '', //金额
        phoneStr2: '', //手机端显示

        month3: '', //月份
        discount3: '', //折扣
        money3: '', //金额
        phoneStr3: '', //手机端显示

        month4: '', //月份
        discount4: '', //折扣
        money4: '', //金额
        phoneStr4: '' //手机端显示
      },
      moneyOption: {
        //金额优惠
        unitPrice: '', //单价
        month1: '', //月份
        money1: '', //金额
        phoneStr1: '', //手机端显示
        month2: '', //月份
        money2: '', //金额
        phoneStr2: '', //手机端显示
        month3: '', //月份
        money3: '', //金额
        phoneStr3: '', //手机端显示
        month4: '', //月份
        money4: '', //金额
        phoneStr4: '' //手机端显示
      },
      discountRules: {
        //折扣优惠rules
        unitPrice: [
          {
            required: true,
            message: '不能为空',
            trigger: ['blur', 'change']
          }
        ],
        month1: [
          {
            type: 'number',
            min: 1,
            max: 12,
            message: '请填写正确的日期',
            trigger: ['blur', 'change']
          }
        ],
        discount1: [
          {
            required: true,
            message: '不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      moneyRules: {
        //金额优惠rules
        unitPrice: [
          {
            required: true,
            message: '不能为空',
            trigger: ['blur', 'change']
          }
        ],
        month1: [
          {
            type: 'number',
            min: 1,
            max: 12,
            message: '请填写正确的日期',
            trigger: ['blur', 'change']
          }
        ]
      },
      picPath: {
        sellingPicPath: '',
        selloutPicPath: ''
      },
      entity: {
        id: null,
        name: '',
        description: '',
        parkList: [],
        vipSeq: '',
        vipName: '',
        maxCarNum: '',
        availableParkCodeList: [],
        sellFromTo: '',
        activeTimeFromTo: '',
        originalPriceMonthly: '',
        realPriceMonthly: '',
        pic: '',
        remark: ''
      },
      tableData: {
        parkItems: [] //通过停车场的ID请求到的停车场对应的VIP类型的列表
      },
      xxx: [],
      picShow: {
        sellingPicShow: '',
        selloutPicShow: ''
      },
      rules: {
        financialParkId: [
          {
            required: true,
            message: '请选择财务主体',
            trigger: 'change'
          }
        ],
        ticketName: [
          {
            required: true,
            message: '月票名称不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: ['blur', 'change']
          }
        ],
        price: [
          {
            required: true,
            message: '请输入单价',
            trigger: 'blur'
          },
          {
            validator: validatePrice,
            trigger: ['change','blur']
          }
        ],
        maxSellNum: [
          {
            required: true,
            message: '请输入数量'
          },
          {
            validator: validateMaxSellNum,
            trigger: ['blur', 'change']
          }
        ],
        sellFromTo: [
          {
            validator: validateSellFromTo,
            trigger: 'change'
          }
        ],
        parkJson: [
          {
            validator: validateParkJson,
            trigger: ['blur', 'change']
          }
        ],
        remark: [
          {
            max: 100,
            message: '最多100 个字符',
            trigger: ['blur', 'change']
          }
        ],
        inviteCarTotal: [
          {
            validator: validateInviteCarTotal,
            trigger: ['blur', 'change']
          }
        ],
        renewFormerDays: [
          {
            validator: validateRenewFormerDays,
            trigger: ['blur', 'change']
          }
        ],
        priTimeArr: [
          {
            required: true,
            message: '请选择时间段'
          }
        ],
        priTimeArrFrom: [
          {
            required: true,
            message: '请选择开始时间'
          }
        ],
        priTimeArrTo: [
          {
            required: true,
            message: '请选择结束时间'
          }
        ],
        vipFullLimitValue: [
          {
            required: true,
            message: '请填写满位控制数量'
          },
          {
            type: 'number',
            message: '该字段必须为数字值'
          }
        ]
      },
      // 月票类型-查看obj
      monthTicketCheckObj: {
        tabName: '',
        basicData: {
          ticketName: '',
          channelArr: [], //所选通道
          financialSubject: '', //财务主体
          monthTicketTypeName: '', //月票类型名称
          price: null, //月票单价
          num: null, //月票数量
          effectiveType: '', //有效期类型
          remark: '' //备注
        },
        superiorData: {
          onlineOpen: '', //线上开通
          monthTicketProof: '', //月票凭证
          overduePaid: '', //过期续费

          overduePaidType: '', //过期续费类型
          overduePaidArr: [], //续费数组

          overduePaidDays: null, //向前续费天数
          virtualCarCode: '', //无牌车
          visitorEmpower: '', //访客授权

          moreCarMoreSeat: '', //是否支持多车多位
          autoSwitchVip: '', //是否支持场内切换
          dynamicFullLimit: '', //是否支持内场多位多车满位到剩余

          openVipFullLimit: '', //是否支持满位控制
          vipFullLimitValue: '', //最多可进多少辆车
          vipFullOpenModel: '', //满位放行模式

          isDatePrivilege: '', //是否按日期
          priDateArrStr: '', //已选择的日期

          isTimePrivilege: '', //是否按时间段
          timeSlot: '', //时间段

          iScharging: '', //是否计费
          offLine: '' //是否支持离线月票
        }
      },
      settings: {
        check: {
          enable: true,
          chkboxType: {
            Y: 'ps',
            N: 'ps'
          }
        },
        data: {
          simpleData: {
            enable: true
          },
          key: {
            children: 'childrenList'
          }
        },
        view: {
          showIcon: false,
          showLine: false
        },
        callback: {
          onCheck: this.setChkDisabledEvent
        }
      }
    };
  },
  created() {
    this.getAllTreeData()
  },
  mounted() {
    let _this = this;
    _this.showMessage_ = deepCopyObj(_this.showMessage);
    _this.listenFileChange();
    _this.getTicketNameList();
    _this.selectAllCertifiRule(); //月票凭证
  },
  computed: {
    discountMoney1: function() {
      return parseFloat(
        this.mouthTicketData.baseTicketData.price * (this.discountOption.discount1 * 0.1) * this.discountOption.month1
      )
        .toFixed(3)
        .slice(0, -1);
    },
    discountMoney2: function() {
      return parseFloat(
        this.mouthTicketData.baseTicketData.price * (this.discountOption.discount2 * 0.1) * this.discountOption.month2
      )
        .toFixed(3)
        .slice(0, -1);
    },
    discountMoney3: function() {
      return parseFloat(
        this.mouthTicketData.baseTicketData.price * (this.discountOption.discount3 * 0.1) * this.discountOption.month3
      )
        .toFixed(3)
        .slice(0, -1);
    },
    discountMoney4: function() {
      return parseFloat(
        this.mouthTicketData.baseTicketData.price * (this.discountOption.discount4 * 0.1) * this.discountOption.month4
      )
        .toFixed(3)
        .slice(0, -1);
    },
    money1: function() {
      return parseFloat(this.mouthTicketData.baseTicketData.price * this.moneyOption.month1)
        .toFixed(3)
        .slice(0, -1);
    },
    money2: function() {
      return parseFloat(this.mouthTicketData.baseTicketData.price * this.moneyOption.month2)
        .toFixed(3)
        .slice(0, -1);
    },
    money3: function() {
      return parseFloat(this.mouthTicketData.baseTicketData.price * this.moneyOption.month3)
        .toFixed(3)
        .slice(0, -1);
    },
    money4: function() {
      return parseFloat(this.mouthTicketData.baseTicketData.price * this.moneyOption.month4)
        .toFixed(3)
        .slice(0, -1);
    }
  },
  methods: {
    // 清空查看月票对象
    clearMonthTicketCheckObj() {
      this.monthTicketCheckObj = {
        tabName: '',
        basicData: {
          ticketName: '',
          channelArr: [], //所选通道
          financialSubject: '', //财务主体
          monthTicketTypeName: '', //月票类型名称
          price: null, //月票单价
          num: null, //月票数量
          effectiveType: '', //有效期类型
          remark: '' //备注
        },
        superiorData: {
          onlineOpen: '', //线上开通
          monthTicketProof: '', //月票凭证
          overduePaid: '', //过期续费

          overduePaidType: '', //过期续费类型
          overduePaidArr: [], //续费数组

          overduePaidDays: null, //向前续费天数
          virtualCarCode: '', //无牌车
          visitorEmpower: '', //访客授权

          moreCarMoreSeat: '', //是否支持多车多位
          autoSwitchVip: '', //是否支持场内切换
          dynamicFullLimit: '', //是否支持内场多位多车满位到剩余

          openVipFullLimit: '', //是否支持满位控制
          vipFullLimitValue: '', //最多可进多少辆车
          vipFullOpenModel: '', //满位放行模式

          isDatePrivilege: '', //是否按日期
          priDateArrStr: '', //已选择的日期

          isTimePrivilege: '', //是否按时间段
          timeSlot: '', //时间段

          iScharging: '', //是否计费
          offLine: '' //是否支持离线月票
        }
      };
    },
    // 月票类型-查看-tab切换
    selectMonthTicketCheckInfoTab(tabName) {
      this.monthTicketCheckObj.tabName = tabName;
    },
    // 月票类型查看
    async monthTicketTypeCheck(rowData) {
      let self = this;
      var params = {};
      params.monthTicketConfigId = rowData.id;
      self.clearMonthTicketCheckObj(); //清空查看月票对象
      self.monthTicketCheckObj.tabName = 'basicTab';
      await self.fetchMonthTicketType(params);
      self.modalStatus = 3;
      self.toOpenModal('monthTicketTypeCheck');
    },
    // 月票类型查看填充数据
    fetchMonthTicketType(params) {
      let self = this;
      return API.fetchGet('/monthTicketBill/configDetail.do', params).then(
        res => {
          if (res.data) {
            let data = res.data;
            self.monthTicketCheckObj.basicData.ticketName = data.ticketName;
            self.monthTicketCheckObj.basicData.monthTicketTypeName = data.ticketName;
            self.monthTicketCheckObj.basicData.price = data.price;
            self.monthTicketCheckObj.basicData.num = data.maxSellNum;
            self.monthTicketCheckObj.basicData.effectiveType =
              data.renewMethod == 'NATURAL_MONTH' ? '自然月' : data.renewMethod == 'CUSTOM' ? '自定义' : '';
            self.monthTicketCheckObj.basicData.remark = data.remark;
            self.monthTicketCheckObj.superiorData.onlineOpen =
              data.ticketType == 'OUTTER' ? '允许' : data.ticketType == 'INNER' ? '不允许' : ''; //线上开通
            self.monthTicketCheckObj.superiorData.overduePaid = data.renew == 1 ? '允许' : '不允许'; //过期续费
            self.monthTicketCheckObj.superiorData.renewFormerDays = data.renewFormerDays; //向前续费天数
            self.monthTicketCheckObj.superiorData.virtualCarCode = data.supportVirtualCarcode == 1 ? '支持' : '不支持'; //无牌车
            self.monthTicketCheckObj.superiorData.visitorEmpower = data.inviteCarTotal; //访客授权-多少个车位
            self.monthTicketCheckObj.superiorData.moreCarMoreSeat =
              data.parkVipType.isDynamicMode == 1 ? '支持' : '不支持'; //多车多位
            self.monthTicketCheckObj.superiorData.autoSwitchVip =
              data.parkVipType.autoSwitchVip == 1 ? '支持' : '不支持'; //多车多位-是否支持场内切换
            self.monthTicketCheckObj.superiorData.dynamicFullLimit =
              data.parkVipType.dynamicFullLimit == 1 ? '支持' : '不支持'; //多车多位-是否支持场内多位多车满位到剩余
            self.monthTicketCheckObj.superiorData.openVipFullLimit =
              data.parkVipType.openVipFullLimit == 1 ? '支持' : '不支持'; //满位控制
            self.monthTicketCheckObj.superiorData.vipFullLimitValue = data.parkVipType.vipFullLimitValue; //最多可进多少辆车
            self.monthTicketCheckObj.superiorData.vipFullOpenModel = data.parkVipType.vipFullOpenModel; //满位放行模式
            self.monthTicketCheckObj.superiorData.isTimePrivilege =
              data.parkVipType.isTimePrivilege == 1 ? '支持' : '不支持'; //是否时间段
            self.monthTicketCheckObj.superiorData.timeSlot = data.parkVipType.privilegeTimePeriod; //时间段
            self.monthTicketCheckObj.superiorData.isDatePrivilege =
              data.parkVipType.isDatePrivilege == 1 ? '支持' : '不支持'; //是否按日期
            self.monthTicketCheckObj.superiorData.priDateArrStr = data.parkVipType.priDateArrStr; //日期控件数据
            self.monthTicketCheckObj.superiorData.iScharging = data.parkVipType.isChargeGroupRelated == 1 ? '是' : '否'; //是否计费
            self.monthTicketCheckObj.superiorData.offLine = data.parkVipType.offLine === 1 ? '支持' : '不支持'; //是否支持离线月票
            self.monthTicketCheckObj.superiorData.overduePaidType = '无优惠';
            let monthTicketContinueBuyList = data.monthTicketContinueDiscountList;
            if (monthTicketContinueBuyList && monthTicketContinueBuyList.length > 0) {
              //连续续费优惠方式
              if (monthTicketContinueBuyList[0].continuDiscountType == 0) {
                //折扣优惠
                self.monthTicketCheckObj.superiorData.overduePaidType = '折扣优惠';
              } else if (monthTicketContinueBuyList[0].continuDiscountType == 1) {
                //金额优惠
                self.monthTicketCheckObj.superiorData.overduePaidType = '金额优惠';
              }
              for (let i = 0; i < monthTicketContinueBuyList.length; i++) {
                let obj = monthTicketContinueBuyList[i];
                let tmpObj = {};
                if (obj.continuDiscountType === 0) {
                  //折扣优惠
                  tmpObj.month = obj.continuMonth; //续费月数
                  tmpObj.discount = obj.discount; //折扣
                  tmpObj.totalPrice = obj.amountMoney; //总价
                  tmpObj.phoneStr = obj.remark; //手机端显示
                } else {
                  //金额优惠
                  tmpObj.month = obj.continuMonth; //续费月数
                  tmpObj.totalPrice = obj.amountMoney; //总价
                  tmpObj.phoneStr = obj.remark; //手机端显示
                }
                self.monthTicketCheckObj.superiorData.overduePaidArr.push(tmpObj); //续费数组
              }
            }
            if (data.certifiRuleId) {
              //月票凭证
              for (let i = 0; i < self.options4.length; i++) {
                if (data.certifiRuleId == self.options4[i].key) {
                  self.monthTicketCheckObj.superiorData.monthTicketProof = self.options4[i].label;
                  break;
                }
              }
            }
            if (data.maxSellLimit == 'YES') {
              //月票数量
              self.monthTicketCheckObj.basicData.num += '份(有限)';
            } else {
              self.monthTicketCheckObj.basicData.num = '无限';
            }
            self.tableData.parkItems = [];
            if (data.parkList) {
              for (let i = 0; i < data.parkList.length; i++) {
                data.parkList[i].parkSysType = data.parkSysType
                self.tableData.parkItems.push(data.parkList[i]); //填充数据
                if (data.parkList[i] && data.parkList[i].parkId == data.financialParkId) {
                  self.monthTicketCheckObj.basicData.financialSubject = data.parkList[i].parkName;
                }
              }
            }
            //查询计费组
            if(data.parkSysType===1){
              self.selectChargeGroupList();
            }
            if (data.channelArr) {
              let arr = {};
              self.monthTicketCheckObj.basicData.channelArr = [];
              for (let i = 0; i < data.channelArr.length; i++) {
                let parkName = data.channelArr[i].parkName;
                let channelName = data.channelArr[i].name;
                if (arr.hasOwnProperty(data.channelArr[i].parkName)) {
                  arr[parkName].push(channelName);
                } else {
                  arr[parkName] = [];
                  arr[parkName].push(channelName);
                }
              }
              for (let key in arr) {
                if (arr.hasOwnProperty(key)) {
                  let obj = {
                    parkName: key,
                    channelName: arr[key].join('/')
                  };
                  self.monthTicketCheckObj.basicData.channelArr.push(obj);
                }
              }
            }
          }
        },
        err => {}
      );
    },
    // 显示及语音
    textVoice(rowData, modalName) {
      let self = this;
      var params = {};
      params.monthTicketConfigId = rowData.id;
      API.monthTicket.manageDetail(params).then(
        res => {
          self.initMouthData_edit(res.data, true);
        },
        err => {}
      );
      self.toOpenModal('textVoiceModal');
    },
    // 添加折扣优惠块
    addDiscountChunk() {
      let len = this.discountIndexArr.length;
      if (len >= 4) {
        return;
      }
      this.discountIndexArr.push(len + 1);
    },
    // 删除金额优惠块
    closeDiscountChunk(idx) {
      this.discountIndexArr.splice(idx, 1);
    },
    // 添加折扣优惠块
    addMoneyChunk() {
      let len = this.moneyIndexArr.length;
      if (len >= 4) {
        return;
      }
      this.moneyIndexArr.push(len + 1);
    },
    // 删除折扣优惠块
    closeMoneyChunk(idx) {
      this.moneyIndexArr.splice(idx, 1);
    },
    // 获取月票名称列表
    getTicketNameList() {
      let self = this;
      let params = {}
      if(self.otherParams.hasOwnProperty(self.paramName) && self.otherParams[self.paramName]){
        params.parkIds = self.otherParams[self.paramName]
      }
      API.fetchGet('/commonFun/monthticket/findConfigNameList.do', params).then(
        res => {
          let data = res.data ? res.data : [];
          let ticketNameList = [];
          ticketNameList.push({ name: '--全部--', value: '' });
          for (let i = 0; i < data.length; i++) {
            ticketNameList.push({
              name: data[i],
              value: data[i]
            });
          }
          self.searchList[0].value = '';
          self.searchList[0].options = ticketNameList;
        },
        err => {}
      );
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getMonthTicketManageList(params);
    },
    getMonthTicketManageList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.monthTicket.GetMonthTicketManageData(params).then(
        res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        },
        err => {}
      );
    },
    getBase64Data(idName) {
      var _this = this;
      var reader = new FileReader();
      var file = document.getElementById(idName).files[0];
      reader.readAsDataURL(file);
      if (!/image\/\w+/.test(file.type)) {
        _this.showToast('请确保上传的文件为图像', 2);
        return false;
      }
      reader.addEventListener('loadend', function() {
        console.log('读取结束', this.result.split('base64,')[1]);
        var base64Data = this.result;
        if (idName == 'traderSelling') {
          _this.mouthTicketData.baseTicketData.sellingPic = base64Data.split('base64,')[1];
          _this.mouthTicketData.baseTicketData.sellingPicName = file.name;
          _this.picShow.sellingPicShow = base64Data;
        }
        if (idName == 'traderSellout') {
          _this.mouthTicketData.baseTicketData.selloutPic = base64Data.split('base64,')[1];
          _this.mouthTicketData.baseTicketData.selloutPicName = file.name;
          _this.picShow.selloutPicShow = base64Data;
        }
      });
    },
    listenFileChange() {
      let _this = this;
      $(document).on('change', '#traderSelling', function() {
        _this.getBase64Data('traderSelling');
      });
      $(document).on('change', '#traderSellout', function() {
        _this.getBase64Data('traderSellout');
      });
    },
    // 设置日期表相关函数 start
    openCalendar() {
      this.toOpenModal('multiCalendarModal');
    },
    saveCalendar(calendar) {
      this.vipTypeData.priDateArrStr = calendar;
      this.closed('multiCalendarModal');
    },
    // 创建月票类型-初始化数据
    initMouthData_create() {
      var self = this;
      self.enableParkSysType = false;
      self.discountIndexArr = [1];
      self.moneyIndexArr = [1];
      self.showMessage = deepCopyObj(self.showMessage_);

      self.discountOption = {
        //折扣优惠
        unitPrice: '', //单价
        month1: '', //月份
        discount1: '', //折扣
        money1: '', //金额
        phoneStr1: '', //手机端显示

        month2: '', //月份
        discount2: '', //折扣
        money2: '', //金额
        phoneStr2: '', //手机端显示

        month3: '', //月份
        discount3: '', //折扣
        money3: '', //金额
        phoneStr3: '', //手机端显示

        month4: '', //月份
        discount4: '', //折扣
        money4: '', //金额
        phoneStr4: '' //手机端显示
      };
      self.moneyOption = {
        //金额优惠
        unitPrice: '', //单价
        month1: '', //月份
        money1: '', //金额
        phoneStr1: '', //手机端显示
        month2: '', //月份
        money2: '', //金额
        phoneStr2: '', //手机端显示
        month3: '', //月份
        money3: '', //金额
        phoneStr3: '', //手机端显示
        month4: '', //月份
        money4: '', //金额
        phoneStr4: '' //手机端显示
      };
      this.mouthTicketData.baseTicketData = {
        id: '',
        parkSysType: '', //停车场类型(0:vems;1:智泊云;100:路边停车)
        ticketName: '', //月票名称
        ticketType: 'OUTTER', //线上开通(INNER:对内月票;OUTTER:对外月票)
        renew: 1, //过期续费 0:不允许;1:允许(默认是1)
        price: '', //月票单价
        renewMethod: 'NATURAL_MONTH', //有效期类型
        maxSellLimit: 'NO', //月票数量(有限/无限)
        maxSellNum: '', //月票数量
        sellNum: '', //已售数量
        financialParkId: '', //记录哪一个停车场为财务主体
        parkJson: [], //每条记录都记录 停车场的ID和对应的VIP类型的关系
        remark: '', //备注
        renewFormerDays: 0, //向前续费天数
        inviteCarTotal: 3, //访客授权车位数
        certifiRuleId: '', //月票凭证
        continueBuyFlag: 1, //连续续费方式
        supportVirtualCarcode: 0, //无牌车(0:不支持;1:支持)
        offLine: 1, //离线月票(0:不支持;1:支持)
        ticketDesc: '',
        sellFromTo: [],
        sellingPic: '',
        selloutPic: '',
        sellingPicName: '',
        selloutPicName: '',
        parkVipTypeJson: ''
      };
      self.vipTypeData = {
        id: null,
        customVipName: '',
        settlementType: 0,
        settlementAmount: null,
        isDynamicMode: 0,
        dynamicCarportNumber: null,
        isDatePrivilege: 0,
        isTimePrivilege: 0,
        privilegeTimePeriod: null,
        isChargeGroupRelated: 0,
        chargeGroupCode: null,
        vipGroupType: 0,
        dynamicFullLimit: 0,
        dynamicCarNumber: null,
        vipNearExpiredDayThreshold: '10',
        vipDeleteExpiredDayThreshold: 0,
        openVipFullLimit: 0,
        vipFullLimitValue: 0,
        vipFullOpenModel: 0,
        vipRecoverTime: null,
        priTimeArr: self.today,
        priTimeArrFrom: '',
        priTimeArrTo: '',
        priDateArrStr: '',
        parkId: '',
        parkName: '',
        channelAuthTree: '',
        channelSeqList: [],
        autoSwitchVip: 0,
        offLine: 1 //离线月票(0:不支持;1:支持)
      };
      this.picPath = {
        sellingPicPath: '',
        selloutPicPath: ''
      };
      this.picShow = {
        sellingPicShow: '',
        selloutPicShow: ''
      };
      this.tableData = {
        parkItems: []
      };
      this.entity.parkList = [];
      self.selectedParkingLot = [];
      self.selectedParkingLotStr = '';
    },
    // 编辑时初始化数据
    initMouthData_edit(rowData, isTextVoice) {
      var self = this;
      self.initMouthData_create();
      self.enableParkSysType = true;
      // 转化时间戳
      var sellFrom = self.formatTime(rowData.sellFrom);
      var sellTo = self.formatTime(rowData.sellTo);

      self.discountOption = {
        //折扣优惠
        unitPrice: '', //单价 validateNumber
        month1: '', //月份 validateMonthNum
        discount1: '', //折扣  validateDiscount
        money1: '', //金额
        phoneStr1: '', //手机端显示

        month2: '', //月份
        discount2: '', //折扣
        money2: '', //金额
        phoneStr2: '', //手机端显示

        month3: '', //月份
        discount3: '', //折扣
        money3: '', //金额
        phoneStr3: '', //手机端显示

        month4: '', //月份
        discount4: '', //折扣
        money4: '', //金额
        phoneStr4: '' //手机端显示
      };

      self.moneyOption = {
        //金额优惠
        unitPrice: '', //单价
        month1: '', //月份
        money1: '', //金额
        phoneStr1: '', //手机端显示
        month2: '', //月份
        money2: '', //金额
        phoneStr2: '', //手机端显示
        month3: '', //月份
        money3: '', //金额
        phoneStr3: '', //手机端显示
        month4: '', //月份
        money4: '', //金额
        phoneStr4: '' //手机端显示
      };

      let continueBuyFlag = 1;
      let monthTicketContinueBuyList = rowData.monthTicketContinueDiscountList;
      if (monthTicketContinueBuyList && monthTicketContinueBuyList.length > 0) {
        //连续续费优惠方式
        if (monthTicketContinueBuyList[0].continuDiscountType == 0) {
          //折扣优惠
          continueBuyFlag = 2;
        } else if (monthTicketContinueBuyList[0].continuDiscountType == 1) {
          //金额优惠
          continueBuyFlag = 3;
        }
        for (let i = 0; i < monthTicketContinueBuyList.length; i++) {
          let obj = monthTicketContinueBuyList[i];
          switch (obj.sort) {
            case 1:
              if (obj.continuDiscountType == 0) {
                //折扣优惠
                self.discountOption.unitPrice = obj.price;
                self.discountOption.month1 = obj.continuMonth;
                self.discountOption.discount1 = obj.discount;
                self.discountOption.phoneStr1 = obj.remark;
                self.discountIndexArr[0] = 1;
              } else if (obj.continuDiscountType == 1) {
                //金额优惠
                self.moneyOption.unitPrice = obj.price;
                self.moneyOption.month1 = obj.continuMonth;
                self.moneyOption.phoneStr1 = obj.remark;
                self.moneyOption.money1 = obj.amountMoney;
                self.moneyIndexArr[0] = 1;
              }
              break;
            case 2:
              if (obj.continuDiscountType == 0) {
                self.discountOption.month2 = obj.continuMonth;
                self.discountOption.discount2 = obj.discount;
                self.discountOption.phoneStr2 = obj.remark;
                self.discountIndexArr[1] = 2;
              } else if (obj.continuDiscountType == 1) {
                self.moneyOption.month2 = obj.continuMonth;
                self.moneyOption.phoneStr2 = obj.remark;
                self.moneyOption.money2 = obj.amountMoney;
                self.moneyIndexArr[1] = 2;
              }
              break;
            case 3:
              if (obj.continuDiscountType == 0) {
                self.discountOption.month3 = obj.continuMonth;
                self.discountOption.discount3 = obj.discount;
                self.discountOption.phoneStr3 = obj.remark;
                self.discountIndexArr[2] = 3;
              } else if (obj.continuDiscountType == 1) {
                self.moneyOption.month3 = obj.continuMonth;
                self.moneyOption.phoneStr3 = obj.remark;
                self.moneyOption.money3 = obj.amountMoney;
                self.moneyIndexArr[2] = 3;
              }
              break;
            case 4:
              if (obj.continuDiscountType == 0) {
                self.discountOption.month4 = obj.continuMonth;
                self.discountOption.discount4 = obj.discount;
                self.discountOption.phoneStr4 = obj.remark;
                self.discountIndexArr[3] = 4;
              } else if (obj.continuDiscountType == 1) {
                self.moneyOption.month4 = obj.continuMonth;
                self.moneyOption.phoneStr4 = obj.remark;
                self.moneyOption.money4 = obj.amountMoney;
                self.moneyIndexArr[3] = 4;
              }
              break;
          }
        }
      }
      self.mouthTicketData.baseTicketData = {
        id: rowData.id,
        parkSysType: rowData.parkSysType + '',
        price: rowData.price,
        ticketName: rowData.ticketName,
        ticketType: rowData.ticketType,
        ticketDesc: rowData.ticketDesc,
        renewMethod: rowData.renewMethod,
        maxSellLimit: rowData.maxSellLimit,
        maxSellNum: rowData.maxSellNum,
        sellNum: rowData.sellNum, //售卖的数量
        remark: rowData.remark,
        renewFormerDays: rowData.renewFormerDays,
        renew: rowData.renew,
        inviteCarTotal: rowData.inviteCarTotal,
        sellFromTo: [new Date(sellFrom), new Date(sellTo)],
        financialParkId: rowData.financialParkId,
        certifiRuleId: rowData.certifiRuleId,
        continueBuyFlag: continueBuyFlag,
        supportVirtualCarcode: rowData.supportVirtualCarcode,
        offLine: rowData.parkVipType.offLine
      };
      self.picShow = {
        sellingPicShow: rowData.sellingPic,
        selloutPicShow: rowData.selloutPic
      };
      self.entity.parkList = [];
      self.tableData.parkItems = [];
      for (let i = 0; i < rowData.parkList.length; i++) {
        //财务主体
        rowData.parkList[i].parkSysType = rowData.parkSysType
        self.tableData.parkItems.push(rowData.parkList[i]);
        self.entity.parkList.push(rowData.parkList[i]);
      }

      copyObjBySelf(self.vipTypeData, rowData.parkVipType); //高级设置
      self.showMessage = JSON.parse(rowData.showMessage); //显示及语音

      let channelArr =
        rowData.channelArr && rowData.channelArr.length ? JSON.parse(JSON.stringify(rowData.channelArr)) : [];
      let channelArrTmp = [];
      let selectedParkingLotStrTmp = [];
      for (let i = 0; i < channelArr.length; i++) {
        let obj = channelArr[i];
        if (channelArrTmp.hasOwnProperty(obj.parkName)) {
          channelArrTmp[obj.parkName].push(obj);
        } else {
          channelArrTmp[obj.parkName] = [];
          channelArrTmp[obj.parkName].push(obj);
        }
      }
      for (let key in channelArrTmp) {
        if (channelArrTmp.hasOwnProperty(key)) {
          selectedParkingLotStrTmp.push(key);
          self.selectedParkingLot.push({
            parkId: channelArrTmp[key][0].parkId,
            name: channelArrTmp[key][0].parkName,
            open: true,
            children: channelArrTmp[key]
          });
        }
      }
      self.vipTypeData.channelAuthTree = JSON.stringify(channelArr);

      self.selectedParkingLotStr = selectedParkingLotStrTmp.join('/');

      // 按时段
      if (
        rowData.parkVipType.isTimePrivilege == 1 &&
        rowData.parkVipType.privilegeTimePeriod &&
        null != rowData.parkVipType.privilegeTimePeriod &&
        '' != rowData.parkVipType.privilegeTimePeriod
      ) {
        self.vipTypeData.priTimeArrFrom = new Date(
          moment().format('YYYY-MM-DD ' + rowData.parkVipType.privilegeTimePeriod.split('-')[0] + ':00')
        );
        self.vipTypeData.priTimeArrTo = new Date(
          moment().format('YYYY-MM-DD ' + rowData.parkVipType.privilegeTimePeriod.split('-')[1] + ':59')
        );
      }

      if (!isTextVoice && rowData.parkSysType===1) {
        //查询计费组
        self.selectChargeGroupList();
      }
    },
    selectMonthTicketInfoTab(tabName) {
      this.mouthTicketData.tabName = tabName;
    },
    selectAllCertifiRule() {
      var self = this;
      self.options4 = [];
      API.monthTicket.SelectAllCertifiRule({}).then(
        res => {
          var data = res.data;
          if (data) {
            var options4 = [];
            data.forEach(function(item) {
              options4.push({ value: item.id, label: item.certifiName, key: item.id });
            }, this);
            self.options4 = options4;
          }
        },
        err => {
          // self.showToast('获取可用的月票凭证异常', 1, 2000);
        }
      );
    },
    // 创建月票
    createTicket2(modalName, rowData) {
      var self = this;
      self.selectedParkingLot = [];
      self.selectedParkingLotStr = '';
      self.mouthTicketData.ticketModalName = modalName;
      self.selectAllCertifiRule();
      if (modalName.indexOf('创建') > -1) {
        self.modalStatus = 1;
        self.mouthTicketData.tabName = 'basicTab';
      } else if (modalName.indexOf('查看') > -1) {
        self.modalStatus = 3;
        self.mouthTicketData.tabName = 'basicTab';
      } else {
        self.modalStatus = 2;
        self.mouthTicketData.tabName = modalName.indexOf('基础信息') > -1 ? 'basicTab' : 'higherTab';
      }
      modalName.indexOf('创建') > -1 ? self.initMouthData_create() : self.initMouthData_edit(rowData);
      if (modalName.indexOf('创建') > -1) {
        //创建月票
        self.initSelectedParkingLotTreeOfOne('ParkTree'); //只有一个停车场时默认选中该停车场
      }
      self.toOpenModal('monthlyTicketModal');
    },
    // 支持停车场弹框
    supportParkShowModal(row) {
      this.supportParkList = row.parkList;
      this.financialParkId = row.financialParkId;
      this.toOpenModal('supportParkModal');
    },
    // 同步详情弹框
    synchronismDetialModal(row) {
      var self = this;
      self.configId = row.id;
      self.supportParkList = [];
      API.monthTicket
        .findSendStatusList({
          configId: row.id
        })
        .then(
          res => {
            var data = res;
            self.supportParkList = data.data;
          },
          err => {}
        );
      this.toOpenModal('synchronismDetialModal');
    },
    resend(row) {
      var self = this;
      API.monthTicket
        .resendVipTypeToPark({
          sendStatusId: row.id
        })
        .then(
          res => {
            //重新加载同步详情
            API.monthTicket
              .findSendStatusList({
                configId: self.configId
              })
              .then(
                res2 => {
                  var data = res2;
                  self.supportParkList = data.data;
                },
                err2 => {}
              );
            //重新加载同步详情
          },
          err => {}
        );
    },
    // 弹出停车场树选择框
    async openSelectParkModal() {
      var self = this;
      await self.getAllTreeData()
      self.toOpenModal('selectParkModal');
      setTimeout(self.initChannelTree2, 300, 'ParkTree');
    },
    // 查看停车场-表格形式
    initParkTree(treeId) {
      var _this = this;
      API.monthTicket.getParkTree({}).then(
        res => {
          //start..
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: 'checkbox',
                radioType: 'all'
              },
              view: {
                showIcon: false,
                showLine: false
              },
              callback: {
                onClick: function(event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                }
              }
            };
            $.fn.zTree.destroy('ParkTree');

            var treeObj = $.fn.zTree.init($('#ParkTree'), settings, nodes);
            var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
            for (var i = 0; i < _this.entity.parkList.length; i++) {
              var node = treeObj.getNodeByParam('value', _this.entity.parkList[i]);
              if (node) {
                if (node.getParentNode() && !node.getParentNode().open) {
                  treeObj.expandNode(node.getParentNode(), true, true, true);
                }
                treeObj.checkNode(node, true, true);
              }
            }
            treeObj.expandAll(true);
          } else {
            _this.showToast('暂时没有停车场可选', 2, 3000);
          }
          //end..
        },
        err => {}
      );
    },
    // 获取vems停车场树数据
    getVemsParkingLotData() {
      let params = {
        parkId: null,
        vipTypeId: null,
        parkSysType: 0,
        canCheckAll: 1
      };
      return API.fetchPost(this.parkingLotUrl, params);
    },
    // 获取智泊云停车场树数据
    getParkingLotData() {
      let params = {
        parkId: null,
        vipTypeId: null,
        parkSysType: 1,
        canCheckAll: 1
      };
      return API.fetchPost(this.parkingLotUrl, params);
    },
    // 获取路边停车场树数据
    getLoadParkingLotData() {
      let params = {
        parkId: null,
        vipTypeId: null,
        parkSysType: 100,
        canCheckAll: 1
      };
      return API.fetchPost(this.parkingLotUrl, params);
    },
    // 获取停车场-通道树全部数据
    getAllTreeData() {
      let self = this;
      return axios.all([self.getVemsParkingLotData(), self.getParkingLotData(), self.getLoadParkingLotData()]).then(
        axios.spread(function(vems, parkingLot, load) {
          let treeDataArr = [];
          let vemsTreeArr = vems.data ? vems.data : [];
          let parkingLotTreeArr = parkingLot.data ? parkingLot.data : [];
          let loadTreeArr = load.data ? load.data : [];
          parkingLotTreeArr = vemsTreeArr.concat(parkingLotTreeArr);
          treeDataArr = parkingLotTreeArr.concat(loadTreeArr);
          self.parkingLotChannelTreeData = deepCopyObjArray(treeDataArr);
        })
      );
    },
    // 只有一个停车场时默认选中该停车场
    initSelectedParkingLotTreeOfOne(treeName) {
      let self = this;
      let nodes = self.parkingLotChannelTreeData;
      if (nodes && nodes.length == 1) {
        //判断是否只有一个停车场
        self.selectedParkingLotStr = nodes[0].name;
        var treeObj = $.fn.zTree.init($('#' + treeName), self.settings, nodes);
        let selectedNodes = treeObj.getNodesByParam('hasChildren', false, null);
        if (selectedNodes && selectedNodes.length) {
          self.vipTypeData.channelAuthTree = JSON.stringify(selectedNodes);
          self.tableData = {
            parkItems: []
          };
          let obj = {
            parkSysType: selectedNodes[0].parkSysType,
            parkVipTypeId: '',
            parkId: selectedNodes[0].parkId,
            parkUuid: selectedNodes[0].parkUuid,
            parkName: selectedNodes[0].parkName,
            chargeGroupCode: '',
            optionArr: []
          };
          self.tableData.parkItems.push(obj); //财务主体
          self.selectedParkingLot.push({
            parkId: selectedNodes[0].parkId,
            name: selectedNodes[0].parkName,
            open: true,
            children: selectedNodes
          });
          self.mouthTicketData.baseTicketData.financialParkId = selectedNodes[0].parkId
        }
        this.$nextTick(() => {
          this.$forceUpdate();
        });
      }
    },
    // 初始化停车场-通道树
    initChannelTree2(treeName) {
      var self = this;
      var nodes =
        self.parkingLotChannelTreeData && self.parkingLotChannelTreeData.length
          ? deepCopyObjArray(self.parkingLotChannelTreeData)
          : [];
      $.fn.zTree.destroy(treeName);
      var treeObj = $.fn.zTree.init($('#' + treeName), self.settings, []);
      //每次都从数据库获取通道的信息，然后从已保存的channelAuthTree中checked
      if (self.vipTypeData.channelAuthTree && self.vipTypeData.channelAuthTree != '') {
        var selectTreeNodes = JSON.parse(self.vipTypeData.channelAuthTree); //已选的通道节点
        var treeNodes = nodes; //全部节点
        var simpleNodesArray = treeObj.transformToArray(treeNodes); //将全部节点转为普通对象
        for (var i = 0; i < simpleNodesArray.length; i++) {
          var simpleNode = simpleNodesArray[i];
          for (var j = 0; j < selectTreeNodes.length; j++) {
            var treeNode = selectTreeNodes[j];
            if (
              simpleNode.parkId &&
              simpleNode.channelSeq &&
              treeNode.parkId == simpleNode.parkId &&
              treeNode.channelSeq == simpleNode.channelSeq
            ) {
              if (treeNode.areaId) {
                if (treeNode.areaId == simpleNode.areaId && treeNode.parkSysType === simpleNode.parkSysType) {
                  simpleNode.checked = true;
                  break;
                }
              } else if (treeNode.parkSysType === simpleNode.parkSysType) {
                simpleNode.checked = true;
                break;
              }
            }
          }
        }
        nodes = treeNodes;
      }
      treeObj.addNodes(null, 0, nodes);

      //勾选父节点的操作
      var temp_checkNodes = treeObj.getCheckedNodes();
      temp_checkNodes.forEach(function(t) {
        if (!t.hasChildren) {
          treeObj.checkNode(t, true, true);
        }
      }, this);

      treeObj.expandAll(true);
    },
    // 停车场树选项是否可以被选择
    setChkDisabledEvent(event, treeId, treeNode) {
      let treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      let isChecked = treeNode.checked; //是否被选择
      let parkSysType = treeNode.parkSysType; //所属车场类型
      let parkingLotTreeNodes = treeObj.getNodes(); //所有的停车场节点
      let selectedNodes = treeObj.getCheckedNodes(true); //选择的节点
      let selectedNodesLength = selectedNodes.length;
      for (let i = 0; i < parkingLotTreeNodes.length; i++) {
        if (parkingLotTreeNodes[i].parkSysType !== parkSysType) {
          if (!isChecked) {
            //取消选择
            if (!selectedNodesLength) {
              //没有节点被选中
              treeObj.setChkDisabled(parkingLotTreeNodes[i], false, true, true);
            } else {
              treeObj.setChkDisabled(parkingLotTreeNodes[i], true, true, true);
            }
          } else {
            treeObj.setChkDisabled(parkingLotTreeNodes[i], true, true, true);
          }
        } else {
          treeObj.setChkDisabled(parkingLotTreeNodes[i], false, true, true);
        }
      }
    },

    // modal弹框--选择停车场时确认时调用函数
    selectParkSure() {
      var self = this,
        nodes = [],
        treeNodes = [];
      var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      treeNodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      let parkList = new Array();
      let selectedParkListTmp = [];
      for (let i = 0; i < treeNodes.length; i++) {
        //过滤重复的停车场
        let node = treeNodes[i];
        if (node.parkId) {//通道节点
          nodes.push(node);
          parkList[node.parkId] = node;
          // 以停车场为单位进行组合
          if (selectedParkListTmp.hasOwnProperty(node.parkName)) {
            selectedParkListTmp[node.parkName].push(node);
          } else {
            selectedParkListTmp[node.parkName] = [];
            selectedParkListTmp[node.parkName].push(node);
          }
        }
      }
      if (nodes.length <= 0) {
        self.showToast('请选择至少一个通道', 0);
        return;
      }
      // 初始化表格显示数据以及提交的表格参数
      self.tableData = {
        parkItems: []
      };
      self.mouthTicketData.baseTicketData.parkJson = [];
      self.selectedParkingLot = [];
      self.selectedParkingLotStr = '';
      //通道信息json
      self.vipTypeData.channelAuthTree = JSON.stringify(nodes);

      self.entity.parkList = [];
      let itemobjArr = [];
      let parkJson = [];
      for (let key in parkList) {
        if (parkList.hasOwnProperty(key)) {
          itemobjArr.push({
            parkVipTypeId: '',
            parkId: parkList[key].parkId,
            parkUuid: parkList[key].parkUuid,
            parkName: parkList[key].parkName,
            chargeGroupCode: parkList[key].chargeGroupCode,
            optionArr: [],
            parkSysType: parkList[key].parkSysType
          });
          self.entity.parkList.push(parkList[key]);
          parkJson.push(parkList[key].parkName);
        }
      }
      for (let key in selectedParkListTmp) {
        if (selectedParkListTmp.hasOwnProperty(key)) {
          self.selectedParkingLot.push({
            parkId: selectedParkListTmp[key][0].parkId,
            name: selectedParkListTmp[key][0].parkName,
            open: true,
            children: selectedParkListTmp[key]
          });
        }
      }
      self.tableData.parkItems = itemobjArr; //填充数据
      self.selectedParkingLotStr = parkJson.join('/');

      if (itemobjArr && itemobjArr.length === 1) {
        self.mouthTicketData.baseTicketData.financialParkId = itemobjArr[0].parkId;
      } else {
        self.mouthTicketData.baseTicketData.financialParkId = '';
      }
      self.closed('selectParkModal');
      this.$nextTick(() => {
        this.$forceUpdate();
      });
      //查询计费组
      if(self.tableData.parkItems[0].parkSysType===1){
        self.selectChargeGroupList();
      }
    },

    selectChargeGroupList() {
      var self = this;
      if (self.tableData.parkItems) {
        let parkIdList = [];
        self.tableData.parkItems.forEach(function(item_) {
          parkIdList.push(item_.parkUuid);
        }, this);

        API.monthTicket
          .SelectChargeGroupList({
            parkIdList: parkIdList.join(',')
          })
          .then(
            res2 => {
              var data = res2.data;
              var parkItems = self.tableData.parkItems;
              parkItems.forEach(function(parkItem) {
                parkItem.optionArr = [];
                let defaultOption = '';
                for (let key in data) {
                  if (key == parkItem.parkUuid) {
                    let tmpArr = data[key];
                    for (let i = 0; i < tmpArr.length; i++) {
                      tmpArr[i].chargeTypeSeq += '';
                      parkItem.optionArr.push(tmpArr[i]);
                      if (
                        parkItem.chargeGroupCode !== 0 &&
                        parkItem.chargeGroupCode !== '0' &&
                        !parkItem.chargeGroupCode
                      ) {
                        defaultOption = tmpArr[i].chargeTypeSeq == 0 ? tmpArr[i].chargeTypeSeq : defaultOption;
                      }
                    }
                    if (
                      parkItem.chargeGroupCode !== 0 &&
                      parkItem.chargeGroupCode !== '0' &&
                      !parkItem.chargeGroupCode
                    ) {
                      parkItem.chargeGroupCode = defaultOption;
                    }
                  }
                }
              }, this);
              this.chargeGroupRender = false;
              this.$nextTick(() => {
                this.chargeGroupRender = true;
              });
            },
            err2 => {}
          );
      }
    },
    // 删除停车场时调用的函数
    delectSelectParkItem(index, parkId) {
      var _this = this;
      _this.tableData.parkItems.splice(index, 1);
      if (_this.mouthTicketData.baseTicketData.financialParkId == parkId) {
        _this.mouthTicketData.baseTicketData.financialParkId = null;
      }
    },
    // 创建-编辑月票类型保存
    submitForm(formName) {
      var self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          self.saveTicket();
        } else {
          return false;
        }
      });
    },
    // 保存显示及语音
    submitTextVoice(modalName) {
      let self = this;
      let params = deepCopyObj(self.mouthTicketData.baseTicketData);
      delete params.offLine;
      if (null != self.checkLast) {
        params.checkLast = self.checkLast;
      }

      if (self.mouthTicketData.ticketModalName.indexOf('创建') == -1) {
        params['ticketCode'] = '';
      }

      params['parkJson'] = JSON.stringify(self.tableData.parkItems);
      params['sellFrom'] = moment(self.mouthTicketData.baseTicketData.sellFromTo[0]).format('YYYY-MM-DD HH:mm:ss');
      params['sellTo'] = moment(self.mouthTicketData.baseTicketData.sellFromTo[1]).format('YYYY-MM-DD HH:mm:ss');
      var vipTypeData_ = deepCopyObj(self.vipTypeData);

      //收费组
      if (self.vipTypeData.isChargeGroupRelated == 0) {
        vipTypeData_.chargeGroupCode = null;
      }
      //区分时间段
      if (self.vipTypeData.isTimePrivilege && self.vipTypeData.priTimeArrFrom && self.vipTypeData.priTimeArrTo) {
        vipTypeData_.privilegeTimePeriod =
          self.vipTypeData.priTimeArrFrom.Format('hh:mm') + '-' + self.vipTypeData.priTimeArrTo.Format('hh:mm');
      } else {
        vipTypeData_.privilegeTimePeriod = '';
      }

      if (self.vipTypeData.isTimePrivilege && vipTypeData_.privilegeTimePeriod == '') {
        self.showToast('请选择区分时间段范围', 0);
        return;
      }

      params.parkVipTypeJson = JSON.stringify(vipTypeData_);
      params['showMessage'] = JSON.stringify(self.showMessage);
      API.fetchPost('monthTicketConfig/saveShowMessage.do', params).then(
        res => {
          if (res.status == 1) {
            self.showToast('月票修改成功', 1);
            self.closed(modalName);
          }
        },
        err => {}
      );
    },
    // 编辑月票类型
    modifyTicket(ticket, modalName) {
      let self = this;
      this.entity.id = ticket.id;
      this.editTicket(ticket.id, modalName);
    },
    // 编辑月票类型调用函数
    editTicket(ticketId, modalName) {
      var self = this;
      var params = {};
      params.monthTicketConfigId = ticketId;
      API.monthTicket.manageDetail(params).then(
        res => {
          self.createTicket2(modalName, res.data);
        },
        err => {}
      );
    },
    //value为13位的时间戳
    formatTime(value) {
      function addzero(m) {
        return m < 10 ? '0' + m : m;
      }
      var time = new Date(parseInt(value));
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var shi = time.getHours();
      var fen = time.getMinutes();
      var miao = time.getSeconds();
      if (value) {
        return y + '-' + addzero(m) + '-' + addzero(d) + ' ' + addzero(shi) + ':' + addzero(fen) + ':' + addzero(miao);
      }
    },
    //value为13位的时间戳
    formatTime2(value) {
      function addzero(m) {
        return m < 10 ? '0' + m : m;
      }
      var time = new Date(parseInt(value));
      var shi = time.getHours();
      var fen = time.getMinutes();
      var miao = time.getSeconds();
      if (value) {
        return addzero(shi) + ':' + addzero(fen);
      }
    },
    // 保存月票时调用函数
    saveTicket() {
      var self = this;
      if(self.vipTypeData.isChargeGroupRelated){ //计费
        if(Array.isArray(self.tableData.parkItems) && self.tableData.parkItems[0].parkSysType===0){
          for(let i = 0; i<self.tableData.parkItems.length; i++){
            let elem = self.tableData.parkItems[i]
            if(!elem.chargeGroupCode){
              self.showToast('请填写计费组编号',0,1500);
              return;
            }
            if(!/^[0-9]+$/.test(elem.chargeGroupCode)){
              self.showToast('计费组编号只能输入数字',0,1500);
              return;
            }
          }
        }
      }
      var params = deepCopyObj(self.mouthTicketData.baseTicketData);
      self.vipTypeData.offLine = self.mouthTicketData.baseTicketData.offLine;
      delete params.offLine;
      if (null != self.checkLast) {
        params.checkLast = self.checkLast;
      }

      if (self.mouthTicketData.ticketModalName.indexOf('创建') == -1) {
        params['ticketCode'] = '';
      }

      params['parkJson'] = JSON.stringify(self.tableData.parkItems);
      params['sellFrom'] = moment(self.mouthTicketData.baseTicketData.sellFromTo[0]).format('YYYY-MM-DD HH:mm:ss');
      params['sellTo'] = moment(self.mouthTicketData.baseTicketData.sellFromTo[1]).format('YYYY-MM-DD HH:mm:ss');
      var vipTypeData_ = deepCopyObj(self.vipTypeData);

      //收费组
      if (self.vipTypeData.isChargeGroupRelated == 0) {
        vipTypeData_.chargeGroupCode = null;
      }
      // 区分日期
      if(self.vipTypeData.isDatePrivilege && !self.vipTypeData.priDateArrStr){
        self.showToast('请选择区分日期', 0);
        return;
      }

      //区分时间段
      if (self.vipTypeData.isTimePrivilege && self.vipTypeData.priTimeArrFrom && self.vipTypeData.priTimeArrTo) {
        vipTypeData_.privilegeTimePeriod =
          self.vipTypeData.priTimeArrFrom.Format('hh:mm') + '-' + self.vipTypeData.priTimeArrTo.Format('hh:mm');
      } else {
        vipTypeData_.privilegeTimePeriod = '';
      }

      if (self.vipTypeData.isTimePrivilege && !vipTypeData_.privilegeTimePeriod) {
        self.showToast('请选择区分时间段范围', 0);
        return;
      }

      params.parkVipTypeJson = JSON.stringify(vipTypeData_);
      params['showMessage'] = JSON.stringify(self.showMessage);

      //折扣优惠
      if (self.mouthTicketData.baseTicketData.continueBuyFlag == 2) {
        let continueDiscountJson = [];
        let discountOptionParams = deepCopyObj(self.discountOption);
        let discountType = 0; //连续优惠类型(0:折扣优惠,1:金额优惠)
        if (discountOptionParams.month1 != '' && discountOptionParams.discount1 != '') {
          let obj = {};
          obj.sort = 1;
          obj.continuDiscountType = discountType;
          obj.continuMonth = discountOptionParams.month1;
          obj.discount = discountOptionParams.discount1;
          obj.amountMoney = self.discountMoney1;
          obj.remark = discountOptionParams.phoneStr1;
          continueDiscountJson.push(obj);
        }
        if (discountOptionParams.month2 != '' && discountOptionParams.discount2 != '') {
          let obj = {};
          obj.sort = 2;
          obj.continuDiscountType = discountType;
          obj.continuMonth = discountOptionParams.month2;
          obj.discount = discountOptionParams.discount2;
          obj.amountMoney = self.discountMoney2;
          obj.remark = discountOptionParams.phoneStr2;
          continueDiscountJson.push(obj);
        }
        if (discountOptionParams.month3 != '' && discountOptionParams.discount3 != '') {
          let obj = {};
          obj.sort = 3;
          obj.continuDiscountType = discountType;
          obj.continuMonth = discountOptionParams.month3;
          obj.discount = discountOptionParams.discount3;
          obj.amountMoney = self.discountMoney3;
          obj.remark = discountOptionParams.phoneStr3;
          continueDiscountJson.push(obj);
        }
        if (discountOptionParams.month4 != '' && discountOptionParams.discount4 != '') {
          let obj = {};
          obj.sort = 4;
          obj.continuDiscountType = discountType;
          obj.continuMonth = discountOptionParams.month4;
          obj.discount = discountOptionParams.discount4;
          obj.amountMoney = self.discountMoney4;
          obj.remark = discountOptionParams.phoneStr4;
          continueDiscountJson.push(obj);
        }
        params['continueDiscountJson'] = JSON.stringify(continueDiscountJson);
      } else if (self.mouthTicketData.baseTicketData.continueBuyFlag == 3) {
        //金额优惠
        let continueDiscountJson = [];
        let moneyOptionParams = deepCopyObj(self.moneyOption);
        let discountType = 1; //连续优惠类型(0:折扣优惠,1:金额优惠)
        if (moneyOptionParams.month1 != '') {
          let obj = {};
          obj.sort = 1;
          obj.continuDiscountType = discountType;
          obj.continuMonth = moneyOptionParams.month1;
          obj.discount = '';
          obj.amountMoney = moneyOptionParams.money1;
          obj.remark = moneyOptionParams.phoneStr1;
          continueDiscountJson.push(obj);
        }
        if (moneyOptionParams.month2 != '') {
          let obj = {};
          obj.sort = 2;
          obj.continuDiscountType = discountType;
          obj.continuMonth = moneyOptionParams.month2;
          obj.discount = '';
          obj.amountMoney = moneyOptionParams.money2;
          obj.remark = moneyOptionParams.phoneStr2;
          continueDiscountJson.push(obj);
        }
        if (moneyOptionParams.month3 != '') {
          let obj = {};
          obj.sort = 3;
          obj.continuDiscountType = discountType;
          obj.continuMonth = moneyOptionParams.month3;
          obj.discount = '';
          obj.amountMoney = moneyOptionParams.money3;
          obj.remark = moneyOptionParams.phoneStr3;
          continueDiscountJson.push(obj);
        }
        if (moneyOptionParams.month4 != '') {
          let obj = {};
          obj.sort = 4;
          obj.continuDiscountType = discountType;
          obj.continuMonth = moneyOptionParams.month4;
          obj.discount = '';
          obj.amountMoney = moneyOptionParams.money4;
          obj.remark = moneyOptionParams.phoneStr4;
          continueDiscountJson.push(obj);
        }
        params['continueDiscountJson'] = JSON.stringify(continueDiscountJson);
      } else {
        params['continueDiscountJson'] = '';
      }

      if (self.forceEdit) {
        //强制编辑
        API.monthTicket.manageForceSave(params).then(
          res => {
            let data = res;
            if (data.status == 1) {
              if (data.resultCode != 10) {
                if (self.mouthTicketData.ticketModalName.indexOf('创建') > -1) {
                  self.showToast('月票创建成功', 1);
                } else {
                  self.showToast('月票修改成功', 1);
                }
                self.getList();
                self.closed('monthlyTicketModal');
              } else {
                //dialog,与后台约定resutlcode=10的时候进行询问
                self.showDialog(data.message, '', function() {
                  //确认修改，重新调用
                  self.checkLast = false;
                  self.saveTicket();
                });
              }
            } else {
              self.showToast(data.message, 2);
            }
          },
          err => {}
        );
      } else {
        //普通编辑and创建
        if (self.modalStatus == 1 || (self.modalStatus == 2 && self.mouthTicketData.tabName == 'basicTab')) {
          //创建月票or修改月票(基础信息)
          API.monthTicket.manageSave(params).then(
            res => {
              let data = res;
              if (data.status == 1) {
                if (self.mouthTicketData.ticketModalName.indexOf('创建') > -1) {
                  self.showToast('月票创建成功', 1);
                } else {
                  self.showToast('月票修改成功', 1);
                }
                self.getList();
                self.closed('monthlyTicketModal');
              } else {
                self.showToast(data.message, 2);
              }
            },
            err => {}
          );
        } else if (self.modalStatus == 2 && self.mouthTicketData.tabName == 'higherTab') {
          //高级配置
          API.fetchPost('/monthTicketConfig/saveAdvancedConf.do', params).then(
            res => {
              if (res.status == 1) {
                self.showToast('月票修改成功', 1);
                self.getList();
                self.closed('monthlyTicketModal');
              } else {
                self.showToast(res.message, 2);
              }
            },
            err => {}
          );
        }
      }
    },
    delTicket(ticket) {
      var self = this;
      if (ticket.sellNum > 0 || ticket.ticketStatus == 'VALID') {
        return;
      }
      var params = {
        monthTicketConfigId: ticket.id
      };
      self.showDialog('确认删除该月票?', '', function() {
        API.monthTicket.manageDel(params).then(
          res => {
            self.showToast('删除月票成功', 1);
            self.getList();
          },
          err => {}
        );
      });
    },
    updateStatusTicket(ticket, status) {
      var self = this;
      var params = {
        monthTicketConfigId: ticket.id,
        monthTicketStatus: status
      };

      var type = status == 'VALID' ? '上架' : '下架';
      self.showDialog('确认' + type + '该月票?', '', function() {
        API.monthTicket.manageUpdateStatus(params).then(
          res => {
            self.showToast('操作成功', 1);
            self.getList();
          },
          err => {}
        );
      });
    }
  },
  filters: {
    ticketType: function(val) {
      switch (val) {
        case 'OUTTER':
          return '线上月票';
        case 'INNER':
          return '对内月票';
        default:
          break;
      }
    },
    ticketStatus: function(val) {
      switch (val) {
        case 'INVALID':
          return '未上架';
        case 'VALID':
          return '已上架';
        case 'EXPIRED':
          return '已过期';
        default:
          break;
      }
    },
    renewMethod: function(val, renew) {
      if (!renew) {
        return '不能续费';
      }
      switch (val) {
        case 'NATURAL_MONTH':
          return '自然月';
        case 'CUSTOM':
          return '自定义';
        default:
          break;
      }
    },
    vipFullOpenModel: function(val){
      switch (val) {
        case 0:
          return '系统有空位自动放行，无空位手动放行按VIP计费';
        case 1:
          return '系统有空位自动放行，无空位手动放行按临时车计费';
        case 2:
          return '系统无空位自动放行，按临时车计费';
        default:
          break;
      }
    }
  },
  watch: {
    'tableData.parkItems': function(newMouthTicketData) {
      if (this.$refs.ticketForm) {
        this.$refs.ticketForm.validateField('parkJson');
      }
    },
    // 高级配置-按日期
    'vipTypeData.isDatePrivilege': function(val) {
      if (val) {
        this.mouthTicketData.baseTicketData.offLine = 0;
      }
    },
    // 高级配置-按时段
    'vipTypeData.isTimePrivilege': function(val) {
      if (val) {
        this.mouthTicketData.baseTicketData.offLine = 0;
      }
    },
    // 高级配置-是否计费
    'vipTypeData.isChargeGroupRelated': function(val) {
      if (val) {
        this.mouthTicketData.baseTicketData.offLine = 0;
      }
    }
  }
};
